<?php

namespace app\api\mdl;


use app\model\BanAccount;
use app\model\Blacklist;
use app\model\MemberBuyer;
use app\model\MemberBuyerAcceptFilter;
use app\model\MemberBuyerPlatformInfo;
use app\model\Message;
use app\model\Order;
use app\model\SmsSend;
use app\model\Task;
use app\model\Withdraw;
use lib\libCache;
use lib\libCurl;
use lib\libRemoveImgFileToQiniu;
use lib\libSms;
use lib\libSuperMark;
use lib\libTool;
use think\Db;
use think\Exception;
use think\facade\Config;

class MdlAuto extends MdlBase
{

    private $_redis = NULL;

    private $_key = "sms_send_phone_message_key";

    private $_webKey = "sms_send_phone_web_key";

    private $_sqlLimit = 1000;//数据库一次处理1000条

    private $_smsLimit = 2000;//短信一次批量发2000条

    public function __construct($data = [])
    {
        parent::__construct($data);
        $this->_redis = libCache::redis();
    }

    private function _getUserId($buyerInfo, $key)
    {
        $mdlOrder = new MdlOrder();
        foreach ($buyerInfo as $v) {
            $limitBuytime = $v['limit_buytime'];
            $receiveTime = $v['receive_time'];
            $overTime = $mdlOrder->formatLimitBuyTime($limitBuytime, $receiveTime);
            $exTime = Config::get("config.shopExtTime");
            $maxTime = $overTime + 86400 * $limitBuytime;
            $isOverMinTime = $overTime < time();
            $isOverMaxTime = $maxTime > time();
            if ($isOverMinTime && $isOverMaxTime) {
                $userId = $v['receiverid'];
                $payTime = $mdlOrder->formatLimitBuytimeTimeFormat($receiveTime, $overTime, $exTime);
                $dat = [
                    "uid" => $userId,
                    "pay_time" => $payTime,
                    "pay_format_time" => date("Y-m-d H:i:s", $payTime)
                ];
                $datString = json_encode($dat, JSON_UNESCAPED_UNICODE);
                print_r($datString);
                $this->_redis->zAdd($key, 1, $datString);
            }
        }
        //明天过期
        $time = strtotime("tomorrow");
        $this->_redis->expireAt($key, $time);
    }


    //发送下单提醒（发站内消息）
    private function _sendUserMessageNotice($key)
    {
        $limit = $this->_sqlLimit; //一次查找1000条
        $id = 0;
        $taskTable = Task::$tableName;
        $orderTable = Order::$tableName;
        echo "----------------脚本开始-----------------\n\r";
        echo date("Y-m-d H:i:s", time()) . "\n\r";
        while (TRUE) {
            //预购并且待接单模式
            $mdlBuyer = Db::table($orderTable)
                ->alias('o')
                ->field('o.orderid,t.limit_buytime,o.receive_time,o.receiverid')
                ->leftJoin([$taskTable => 't'], 'o.taskid=t.taskid')
                ->where("o.status", 2);
            if ($id) {
                $mdlBuyer->where("o.orderid", "<", $id);
            }
            $buyerInfo = $mdlBuyer->where('o.tasktype', 5)->order("o.orderid desc")->limit($limit)->select();
            if ($buyerInfo) {
                $id = $buyerInfo[count($buyerInfo) - 1]['orderid'];
                $this->_getUserMessage($buyerInfo, $key);
            } else {
                break;
            }
            usleep(20000);
        }
    }


    private function _getUserMessage($buyerInfo, $key)
    {
        $mdlOrder = new MdlOrder();
        $mdlMessage = new Message();
        $data = [];
        foreach ($buyerInfo as $v) {
            $limitBuytime = $v['limit_buytime'];
            $receiveTime = $v['receive_time'];
            $overTime = $mdlOrder->formatLimitBuyTime($limitBuytime, $receiveTime);
            $maxTime = $overTime + 86400 * $limitBuytime;
            $isOverMinTime = $overTime < time();
            $isOverMaxTime = $maxTime > time();
            if ($isOverMinTime && $isOverMaxTime) {
                $orderId = $v['orderid'];
                $now = date("Y-m-d", time());
                $message = sprintf("您的订单%s为预售任务订单，请在（%s）当日下单付款，请进入待操作查看，逾期没处理将会自动撤销任务。", $orderId, $now);
                $data[] = [
                    "title" => "预购订单操作提醒",
                    "content" => $message,
                    "flag" => 0,
                    "addtime" => date("Y-m-d H:i:s", time()),
                    "userid" => $v['receiverid'],
                    "usertype" => 1
                ];
                $userId = $v['receiverid'];
                $this->_redis->zAdd($key, 1, strval($userId));
            }
        }
        echo "站内信息如下:<pre>\n\r";
        if ($data) {
            print_r($data);
            //todo:插入站内信
            $mdlMessage->insertAll($data);
        }
        //明天过期
        $time = strtotime("tomorrow");
        $this->_redis->expireAt($key, $time);
    }


    //发送站内信息
    public function sendMessage()
    {
        $this->_sendUserMessageNotice($this->_webKey);

        echo date("Y-m-d H:i:s", time()) . "\n\r";
        echo "----------------脚本结束-----------------\n\r";
    }


    //发送短信
    public function sendSmsToRedis()
    {
        $this->_sendSmsToRedis();
        echo date("Y-m-d H:i:s", time()) . "\n\r";
        echo "----------------脚本结束-----------------\n\r";
    }

    //存储信息
    public function saveSendSms()
    {
        $this->_saveUserPaySmsNotice($this->_key);
        echo date("Y-m-d H:i:s", time()) . "\n\r";
        echo "----------------脚本结束-----------------\n\r";
    }

    //发送下单提醒存储到redis(发短信)
    private function _saveUserPaySmsNotice($key)
    {
        $limit = $this->_sqlLimit; //一次查找1000条
        $id = 0;
        $taskTable = Task::$tableName;
        $orderTable = Order::$tableName;
        echo "----------------脚本开始-----------------\n\r";
        echo date("Y-m-d H:i:s", time()) . "\n\r";
        while (TRUE) {
            //预购并且待接单模式
            $mdlBuyer = Db::table($orderTable)
                ->alias('o')
                ->field('o.orderid,t.limit_buytime,o.receive_time,o.receiverid')
                ->leftJoin([$taskTable => 't'], 'o.taskid=t.taskid')
                ->where("o.status", 2);

            if ($id) {
                $mdlBuyer->where("o.orderid", "<", $id);
            }
            $buyerInfo = $mdlBuyer->where('o.tasktype', 5)->order("o.orderid desc")->limit($limit)->select();
            if ($buyerInfo) {
                $id = $buyerInfo[count($buyerInfo) - 1]['orderid'];
                echo "<pre>符合的短信信息如下\n\r";
                $this->_getUserId($buyerInfo, $key);
            } else {
                break;
            }
            usleep(20000);
        }

    }

    //发送短信
    private function _sendSmsToRedis()
    {
        $limit = $this->_smsLimit;
        $end = $limit;
        $start = 0;
        $mdl = new MemberBuyer();
        $smsObject = new libSms();
        echo "----------------脚本开始-----------------\n\r";
        echo date("Y-m-d H:i:s", time()) . "\n\r";
        while (TRUE) {
            $data = $this->_redis->zRange($this->_key, $start, $end, 1);
            if ($data) {
                $idData = array_keys($data);
                //做时间判断
                $idArray = [];
                foreach ($idData as $v) {
                    $dataJson = json_decode($v, 1);
                    $payTime = $dataJson['pay_time'];
                    //当前时间大于付款时间就发短信
                    if (time() > $payTime) {
                        echo sprintf("发送短信时间：%s\n\r", date("Y-m-d H:i:s", $payTime));
                        $this->_redis->zRem($this->_key, $v);
                        $idArray[] = $dataJson['uid'];
                    }
                }
                if ($idArray) {
                    $phoneDataArray = $mdl->field("cellphone,userid")->whereIn("userid", $idArray)->select();
                    $phoneDataArray = $phoneDataArray->toArray();
                    $phoneArray = libTool::mkKey($phoneDataArray, "cellphone");
                    $phone = implode(",", $phoneArray);
                    echo "发送的号码<pre>";
                    print_r($phoneDataArray);
                    echo "\n\r";
                    $smsObject->sendSmsCode($phone, "notice");
                }
                $start = $end + 1;
                $end = $start + $limit;
            } else {
                break;
            }
        }
    }

    private function getGoodSid($url)
    {

        $url = htmlspecialchars_decode($url);
        $url = htmlspecialchars_decode($url);
        $url = htmlspecialchars_decode($url);
        preg_match("/[&,\?]id=(\d*)/is", $url, $stringArray);
        if (isset($stringArray[1])) {
            return $stringArray[1];
        }
        return FALSE;
    }

    //设置sid
    public function setGoodSid()
    {
        $taskModel = new Task();
        $limit = 1000;
        $id = 0;
        echo "--------------------脚本开始(" . date('Y-m-d H:i:s', time()) . ")------------------------------";
        echo "\n\r";
        while (TRUE) {
            $res = $taskModel->field('taskid,url,imgurlex1,imgurlex2')->where("platformtype", 1)->where("taskid", ">", $id)->limit($limit)->select();
            if (!$res) {
                break;
            }
            if ($res && $res->toArray()) {
                $res = $res->toArray();
                foreach ($res as $v) {
                    $taskid = $v['taskid'];
                    if (!$taskid || !isset($v['taskid'])) {
                        continue;
                    }
                    $goodsid = $this->getGoodSid($v['url']);
                    $goodsid1 = $this->getGoodSid($v['imgurlex1']);
                    $goodsid2 = $this->getGoodSid($v['imgurlex2']);
                    $updateData = [];
                    if ($goodsid != "") {
                        $updateData['goodsid'] = $goodsid;
                        echo "goodsid:" . $goodsid;
                    }
                    if ($goodsid1 != "") {
                        $updateData['goodsid1'] = $goodsid1;
                        echo "goodsid1:" . $goodsid1;
                    }
                    if ($goodsid2 != "") {
                        $updateData['goodsid2'] = $goodsid2;
                        echo "goodsid2:" . $goodsid2;
                    }
                    if ($updateData) {
                        try {
                            $updateStatus = $taskModel->where("taskid", $taskid)->update($updateData);
                            echo sprintf("状态：%s,更新完成%s,字段(%s)\n\r", $updateStatus, $taskid, implode(",", array_keys($updateData)));
                        } catch (Exception $e) {
                            print_r($e);
                        }
                    } else {
                        echo sprintf("%s：不需要更新字段\n\r", $taskid);
                    }
                }
                $id = $res[count($res) - 1]['taskid'];
                echo "下一个id是" . $id . '\n\r';

            } else {
                break;
            }
            usleep(20000);

        }
        echo "--------------------END(" . date('Y-m-d H:i:s', time()) . ")------------------------------";
        echo "\n\r";
    }

    //校对性别脚本
    public function updateSex()
    {
        $buyerPlatformInfoModel = new MemberBuyerPlatformInfo();
        $banAccount = new BanAccount();
        $limit = 1000;
        $id = 0;
        $startTime = "2018-10-01 00:00:00";
        $endTime = "2019-08-1 00:00:00";
        echo "--------------------脚本开始(" . date('Y-m-d H:i:s', time()) . ")------------------------------";
        echo "\n\r";
        while (TRUE) {
            $res = $buyerPlatformInfoModel->field('id,userid,account,sex,addtime,status')->where("type", 1)->where("status", 1)->where("addtime", ">=", $startTime)->where("addtime", "<", $endTime)->where("id", ">", $id)->order("id asc")->limit($limit)->select();
            if (!$res) {
                break;
            }
            if ($res && $res->toArray()) {
                $res = $res->toArray();
                foreach ($res as $v) {
                    $sex = $v['sex'];
                    if ($v['sex'] == 1) {
                        $sex = "男";
                    }
                    if ($v['sex'] == 2) {
                        $sex = "女";
                    }
                    $id = $v['id'];
                    $account = $v['account'];
                    $userid = $v['userid'];
                    $substationSelectNick = \tool\Taobao::substationSelectNick($account);
                    if (!isset($substationSelectNick['gender'])) {
                        $substationSelectNick = \tool\Taobao::substationSelectNick($account);
                        if (!isset($substationSelectNick['gender'])) {
                            $substationSelectNick = \tool\Taobao::substationSelectNick($account);
                            if (!isset($substationSelectNick['gender'])) {
                                echo sprintf("账号%s(%s)接口连接错误", $account, $id);
                                echo "\n\r";
                                continue;
                            }
                        }
                    }
                    if ($substationSelectNick['gender'] == "") {
                        $bRes = $buyerPlatformInfoModel->where('id', $id)->update([
                            'status' => 3,
                            "operator" => "system_script",
                            "op_time" => \tool\Date::date(),
                            "op_reason" => "此账号不符合平台绑定要求，不要再申请这个账号绑定了，请更换其他账号进行审核绑定"
                        ]);
                        $bAcc = $banAccount->insert([
                            "userid" => $userid,
                            "account" => $account,
                            "accounttype" => 1,
                            "addtime" => \tool\Date::date()
                        ]);
                        echo sprintf("账号%s(%s)性别为空，驳回，插入状态：status:%s,ban:%s", $account, $id, $bRes, $bAcc);
                        echo "\n\r";
                        continue;
                    }
                    $data = $substationSelectNick['gender'] == "男" ? 1 : 2;
                    if ($substationSelectNick['gender'] != $sex) {
                        echo sprintf("账号%s(%s)性别错误，原：%s 接口：%s", $account, $id, $sex, $substationSelectNick['gender']);
                        echo "\n\r";
                        $updateRes = $buyerPlatformInfoModel->where('id', $id)->update([
                            'sex' => $data
                        ]);
                        echo("更新结果：$updateRes");
                        echo "\n\r";
                    } else {
                        echo sprintf("账号%s(%s)性别正确，原：%s 接口：%s", $account, $id, $sex, $substationSelectNick['gender']);
                        echo "\n\r";
                    }
                }
                $id = $res[count($res) - 1]['id'];
                echo "下一个id是" . $id . '\n\r';
            } else {
                break;
            }
            usleep(20000);
        }
        echo "--------------------END(" . date('Y-m-d H:i:s', time()) . ")------------------------------";
        echo "\n\r";
    }

    //更新access_token
    public function updateAccessToken()
    {
        $superMarkObj = new libSuperMark();
        $accessToken = $superMarkObj->getAccessToken();
        if ($accessToken == -1) {
            echo "access_token更新失败";
            return -1;
        }
        $res = $superMarkObj->setAccessTokenToRedis($accessToken);
        if (!$res) {
            echo "access_token更新redis更新失败";
            return -1;
        }
        echo "获取成功：" . $accessToken;
        return $accessToken;
    }

    //撤单
    public function cancelOrder()
    {
        $mdl = new Order();
        $limit = 1000;
        $id = 0;
        echo "--------------------脚本开始(" . date('Y-m-d H:i:s', time()) . ")------------------------------";
        echo "\n\r";
        while (TRUE) {
            $res = $mdl->field('orderid')->where("status", 299)->where("tasktype", 100)->where("orderid", ">", $id)->limit($limit)->select();
            if (!$res) {
                break;
            }
            if ($res && $res->toArray()) {
                $res = $res->toArray();
                foreach ($res as $v) {
                    $orderid = $v['orderid'];
                    $cres = $mdl->where("orderid", $orderid)->update(['status' => 0]);
                    if ($cres) {
                        echo "已撤销订单：" . $orderid . '\n\r';
                        $this->cOrder($orderid);
                    }
                }
                $id = $res[count($res) - 1]['orderid'];
                echo "下一个id是" . $id . '\n\r';
            } else {
                break;
            }
            usleep(20000);
        }
        echo "--------------------END(" . date('Y-m-d H:i:s', time()) . ")------------------------------";
        echo "\n\r";

    }

    public function cOrder($orderid)
    {
        $money = 0;
        $isover = 2;//1不撤单，2撤单
        $status = 0;
        $operator = "system";
        $note = "系统优化，撤销浏览单";
        $ip = Request()->ip();
        Db::execute("call batch_order('" . $orderid . "'," . $status . "," . $money . ",'" . $ip . "','" . $operator . "'," . $isover . ",'" . $note . "')");
    }

    public function checkPhone()
    {
        $mdl = new MemberBuyer();
        $limit = 1000;
        $id = 0;
        echo "--------------------脚本开始(" . date('Y-m-d H:i:s', time()) . ")------------------------------";
        echo "\n\r";
        while (TRUE) {
            $res = $mdl->field('userid,cellphone')->where("userid", ">", $id)->limit($limit)->select();
            if (!$res) {
                break;
            }
            if ($res && $res->toArray()) {
                $res = $res->toArray();
                foreach ($res as $v) {

                    $phone = $v['cellphone'];
                    $userid = $v['userid'];
                    $url = Config::get("appConfig.zzd_check_register");
                    $url = sprintf("%s?phone=%s", $url, $phone);
                    $data = libCurl::get($url);
                    if (!$data) {
                        echo sprintf("请求失败%s(%s)", $phone, $userid);
                        echo "\n\r";
                        continue;
                    }
                    $data = json_decode($data, 1);
                    //不存在result或者是新用户的时候
                    if ($data['result'] == -1 || !isset($data['result'])) {
                        //新用户
                        echo sprintf("不存在该用户%s(%s)", $phone, $userid);
                        echo "\n\r";
                        continue;
                    }
                    if ($data['result'] == -2 || $data['result'] == -3) {
                        echo sprintf("插入黑名单%s(%s)", $phone, $userid);
                        $blacklistData = [
                            'type' => 1,
                            'value' => $phone,
                            'note' => "为旧平台的黑名单或者限制接单用户，不给通过",
                        ];
                        Blacklist::insert($blacklistData);
                    }
                }
                $id = $res[count($res) - 1]['userid'];
                echo "下一个id是" . $id . '\n\r';
            } else {
                break;
            }
            usleep(20000);
        }
        echo "--------------------END(" . date('Y-m-d H:i:s', time()) . ")------------------------------";
        echo "\n\r";
    }

    //统计累积赚取
    public function sumCountCoin()
    {
        $mdlBuyer = new MemberBuyer();
        $mdlWithdraw = new Withdraw();
        $limit = 1000;
        $id = 0;
        echo "--------------------脚本开始(" . date('Y-m-d H:i:s', time()) . ")------------------------------";
        echo "\n\r";
        while (TRUE) {
            $res = $mdlBuyer->field('userid,count_coin')->where("userid", ">", $id)->limit($limit)->select();
            if (!$res) {
                break;
            }
            if ($res && $res->toArray()) {
                $res = $res->toArray();
                foreach ($res as $v) {
                    $userid = $v['userid'];
                    $countCoin = $v['count_coin'];
                    //统计数量
                    $amount = $mdlWithdraw->where('userid', $userid)
                        ->where('usertype', 1)
                        ->where('type', 2)
                        ->where('status', '<>', 3)
                        ->sum('amount');
                    if (!$amount) {
                        echo "累积赚取为0，不需要更新，用户ID：" . $userid . '原值：' . $countCoin . 'amount：' . $amount . "\n\r";
                        continue;
                    }
                    $sqlUpdate = sprintf("%s+%s", "count_coin", $amount);
                    $updateRes = $mdlBuyer->where("userid", $userid)->update(['count_coin' => Db::raw($sqlUpdate)]);
                    if ($updateRes) {
                        echo "已经更新用户id：" . $userid . '原值：' . $countCoin . 'amount：' . $amount . "\n\r";
                    } else {
                        echo "更新失败用户id：" . $userid . '原值：' . $countCoin . 'amount：' . $amount . "\n\r";
                    }
                    usleep(20000);
                }
                $id = $res[count($res) - 1]['userid'];
                echo "下一个id是" . $id . '\n\r';
            } else {
                break;
            }
            usleep(200000);
        }
        echo "--------------------END(" . date('Y-m-d H:i:s', time()) . ")------------------------------";
        echo "\n\r";
    }

    private $_userArr = [];//短信一次批量发2000条

    public function addLimitToUserid($uid, $userArray = [])
    {
        //        var_dump($uid);
        $mdlBuyer = new MemberBuyer();
        $maxLimit = 1000;
        echo "--------------------脚本开始(" . date('Y-m-d H:i:s', time()) . ")------------------------------";
        echo "\n\r";
        $where = sprintf("`up1_userid` =%s", $uid);
        $limit = $mdlBuyer->field('userid')->where($where)->count();
        if ($limit > $maxLimit) {
            echo "用户ID：$uid 有【 $limit 】个下级  超过最大 限制【 $maxLimit 】 防止数据库卡顿，请谨慎处理，您可以调整$maxLimit 的数量";
            //手动处理数据
            $this->_userArr = [];
            exit();
        }
        $res = $mdlBuyer->field('userid,up1_userid,up2_userid,cellphone')->where($where)->limit($limit)->select();
        if (!$res) {
            return FALSE;
        }

        if ($res && $res->toArray()) {
            $res = $res->toArray();
            foreach ($res as $v) {
                $uid = $v['userid'];
                array_push($this->_userArr, $v);
                $this->addLimitToUserid($uid, $this->_userArr);
                usleep(20000);
            }
            $id = $res[count($res) - 1]['userid'];
            echo "下一个id是" . $id . '\n\r';
        } else {
            return FALSE;
        }
        usleep(200000);
        echo "--------------------END(" . date('Y-m-d H:i:s', time()) . ")------------------------------";
        echo "\n\r";
    }

    //拉黑
    public function addLimit($mode, $uid)
    {
        echo "<pre>";
        if (!$mode || !$this->_userArr) {
            echo "查看限制名单为:";

            print_r($this->_userArr);
            return FALSE;
        }
        echo "已经被加入限制的名单为";
        print_r($this->_userArr);
        foreach ($this->_userArr as $v) {
            if ($mode == 1) {
                //加入限制接单
                $this->_setBuyerAcceptFilter($v['cellphone'], $uid);
            }
            if ($mode == 2) {
                //加入黑名单
                Blacklist::addPhoneToBlackList($v['cellphone'], "检测为用户ID $uid （骗子）带来的下级，加入黑名单");
            }
        }
    }

    //加入限制接单
    private static function _setBuyerAcceptFilter($value, $uid)
    {
        $mdl = new MemberBuyerAcceptFilter();
        $isExt = $mdl->where('value', $value)->where('type', 3)->where("platform", 0)->count();
        if (!$isExt) {
            $acceptFilterData = [
                "platform" => 0,
                "type" => 3,
                'value' => $value,
                "create_at" => \tool\Date::date(),
                "note" => "检测为用户ID $uid （骗子）带来的下级，加入限制接单"
            ];
            return $mdl->insert($acceptFilterData);
        }
        return FALSE;
    }

    private function _uploadQiniu($filePath)
    {
        $option = [
            "filePath" => $filePath, //文件路径
        ];
        try {
            $obj = new libRemoveImgFileToQiniu($option);
            $res = $obj->upload();
            //如果存在code并且是上传成功的
            return $res;
        } catch (\Exception $e) {
            return [
                "code" => 111,
                "data" => [],
                "msg" => $e->getMessage()
            ];
        }
    }

    public function removeImgFile($table, $fieldArray = [], $primaryKey = "")
    {
        if ($primaryKey == "") {
            echo "请定义主键字段";
            exit();
        }
        if (!$fieldArray) {
            echo "请定义图片字段";
            exit();
        }
        $fieldArray[] = $primaryKey;
        $limit = 1000; //一次更新多少条
        $id = 658;
        $dbConf=[
            // 数据库类型
            'type'        => 'mysql',
            // 服务器地址
            'hostname'    => '159.138.45.145',
            // 数据库名
            'database'    => 'sdplatform',
            // 数据库用户名
            'username'    => 'zzd_app',
            // 数据库密码
            'password'    => 'rY^qXeTKG9!zHAIS',
            // 数据库编码默认采用utf8
            'charset'     => 'utf8',
            "prefix"=>""
        ];
        $mdlTable = Db::connect($dbConf)->table($table);
        $field = implode(",", $fieldArray);
      echo "--------------------脚本开始(" . date('Y-m-d H:i:s', time()) . ")------------------------------";
        echo "\n\r";
        while (TRUE) {
            $res = $mdlTable->field($field)->where($primaryKey, ">", $id)->limit($limit)->select();
            if (!$res) {
                break;
            }
            foreach ($res as $v) {
                $tableId = $v[$primaryKey];
                $msg = sprintf("%s:%s ", $primaryKey, $tableId);
                $uploadMsg = "";
                //发布任务
                foreach ($fieldArray as $field) {
                    if ($field === $primaryKey) {
                        continue;
                    }
                    $imgPath =strtr($v[$field], '\\', '/') ;
                        //如果有七牛的前缀,就不需要上传
                    $isPrefix = strpos($imgPath, "qiNiu_");
                    if ($isPrefix) {
                        echo "七牛图片：".$imgPath;
                        $imgPath = "";
                    }
                    //如果图片为空或者不存在就不需要上传
                    if (!libTool::checkEmpty($imgPath) || !$imgPath) {
                        $msg .= sprintf(" %s:%s", $field, "无");
                        continue;
                    }

                    $msg .= sprintf(" %s:%s", $field, "有图片");
                    $uploadRes = $this->_uploadQiniu($imgPath);
                    if ($uploadRes['code'] != 200) {
                       Db::connect($dbConf)->table("tbs_temp_img_remove_error_log")->insert([
                          "code" => $uploadRes['code'], //code
                            "msg" => $uploadRes['msg'],//上传失败的原因
                            "img_field" => $field, //字段
                            "op_table" => $table,
                            "table_id" => $tableId
                        ]);

                        //加入到失败的日志
                        $uploadMsg .= sprintf(" %s,%s,%s", $field, $uploadRes['code'], $uploadRes['msg']);
                    } else {
                        $uploadMsg .= sprintf(" %s,%s,%s", $field, "200", "处理成功");
                    }
                      usleep(20000);
                }
                if($uploadMsg==""){
                    $uploadMsg="无需处理";
                }
                $msg .= sprintf(" 结果：%s", $uploadMsg);
                echo $msg ."\n\r";

            
            }
            $id = $res[count($res) - 1][$primaryKey];
            echo "下一个id是" . $id ."\n\r";
            //尝试一次

            usleep(100000);
        }
        echo "--------------------END(" . date('Y-m-d H:i:s', time()) . ")------------------------------";
        echo "\n\r";
        exit();
    }

}
